import { request } from './request'

export interface ProjectItem {
  id: number
  name: string
  description?: string
  projectTypeName?: string
  projectTypeId?: number
  status?: number
  updatedAt?: string
  createTime?: string
}

interface ProjectListPayload {
  list?: ProjectItem[]
  records?: ProjectItem[]
  data?: ProjectItem[]
}

const normalizeProjectList = (data: ProjectListPayload | ProjectItem[]) => {
  if (Array.isArray(data)) {
    return data
  }
  if (Array.isArray(data?.list)) {
    return data.list
  }
  if (Array.isArray(data?.records)) {
    return data.records
  }
  if (Array.isArray((data as any)?.data)) {
    return (data as any).data
  }
  return []
}

export async function fetchProjectList(params: {
  workspaceId: number
  pageNum?: number
  pageSize?: number
}) {
  const data = await request<ProjectListPayload | ProjectItem[]>({
    url: '/lowcode3/api/project/list',
    data: {
      pageNum: 1,
      pageSize: 200,
      ...params
    }
  })
  return normalizeProjectList(data)
}
